package com.gongj.beanPostPorcessor;


import com.gongj.bean.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

import java.beans.PropertyDescriptor;

public class MyBeanPostPorcessor implements InstantiationAwareBeanPostProcessor {



	// 如果 postProcessBeforeInstantiation 实例化前方法 返回 不是 null
	// 如我这写法，将会中断Spring的创建bean的流程，执行完实例化前方法后，直接执行 postProcessAfterInitialization 初始化后
	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {

		if("person".equals(beanName)){
			System.out.println("实例化前");
			System.out.println("原本class对象:"+beanClass);
		}
		//return new User();
		return null;
	}

	// postProcessAfterInstantiation 实例化后 方法，如果返回 false，将不会对属性进行填充
	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

		if("person".equals(beanName)){
			System.out.println("实例化后");
		}
		return true;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
		if("person".equals(beanName)){
			System.out.println("postProcessProperties方法被执行");
			PropertyValue name = pvs.getPropertyValue("name");
			Object oldValue = name.getValue();
			System.out.println("修改前name的值是:"+oldValue);
			name.setConvertedValue("yuanj");
		}
		return null;
	}

//	@Override
//	public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
//		if("person".equals(beanName)){
//			System.out.println("废弃方法：postProcessPropertyValues被执行");
//			PropertyValue name = pvs.getPropertyValue("name");
//			Object oldValue = name.getValue();
//			System.out.println("修改前name的值是:"+oldValue);
//			name.setConvertedValue("gongjie LOVE  yuanj");
//		}
//		return pvs;
//	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if("person".equals(beanName)){
			System.out.println("初始化前");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

		if("person".equals(beanName)){
			System.out.println("初始化后");
			System.out.println("原本class对象:"+bean);
		}
		return bean;
	}
}
